package com.example.myapplication.ui.mainframe;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.slidingpanelayout.widget.SlidingPaneLayout;

import com.example.myapplication.R;
import com.example.myapplication.bean.Gps;
import com.example.myapplication.service.GpsService;
import com.example.myapplication.ui.component.PageEnabledSlidingPaneLayout;
import com.example.myapplication.ui.execution.ExecutionInput;
import com.example.myapplication.ui.inspection.InspectionCheck;
import com.example.myapplication.ui.inspection.InspectionInput;
import com.example.myapplication.ui.login.LoginActivity;
import com.example.myapplication.ui.task.TaskCheckActivity;


public class MainPageActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout main_page_btn1;//点检情况录入按钮
    private LinearLayout main_page_btn2;//作业指令查看按钮
    private LinearLayout main_page_btn3;//作业过程记录按钮
    private LinearLayout personExit;//用户注销按钮
    private LinearLayout personInfo;//用户信息按钮
    private LinearLayout inspection_input; // 点检录入按钮
    private LinearLayout inspection_check; // 点检查看按钮
    private Switch gpsSwitch;//gps开关
    private static boolean isExit = false;//退出状态标记
    private static LocationManager locationManager;
    private boolean gpsEnable;//gps状态
    private boolean isSecondMenuLoad; // 功能一的二级菜单是否开启
    private final static String TAG = "MainPageActivity";
    private String name;
    private GpsService gpsService;
    private Handler handler;
    private Thread gpsThread;
    /**
     * 侧划控件
     */
    private PageEnabledSlidingPaneLayout slidingPaneLayout;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main_page);
        slidingPaneLayout = (PageEnabledSlidingPaneLayout) findViewById(R.id.sliding_pane_layout_main_page);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        initSlidingPaneLayout();//开启侧边栏
        initView();
        name = getIntent().getStringExtra("name");

    }

    @Override
    protected void onStart() {
        super.onStart();
        getContentResolver().registerContentObserver
                (Settings.Secure.getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED),
                        false, mGpsMonitor);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //gps开关的监听回调方法
        gpsSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    //switch开时候执行的回调
                    boolean gpsIsOpen = checkGPSIsOpen();
                    if (!gpsIsOpen) {
                        enableLocationSettings();
                    }
                    gpsThread = getGpsThread();
                    gpsThread.start();
                    Log.d(TAG, "onCheckedChanged: " + gpsEnable);
                } else {
                    if (gpsThread!= null) {
                        gpsThread.interrupt();
                    }
                }
            }
        });
    }

    private Thread getGpsThread() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                // 在此处添加执行的代码
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        continue;
                    }
                    Integer status = 0;
                    gpsService = new GpsService();
                    Gps gpsInfo = getLatitudeAndLongitude();
                    if (gpsInfo == null) {
                        continue;
                    }
                    status = gpsService.addGpsInfo(gpsInfo);
                    if (status != null)
                        Log.d(TAG, "run: " + status);
                    else {
                        break;
                    }
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        return new Thread(runnable);
    }





    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        checkGPSStates();//重新载入主界面的时候更新gps状态标记
//        gpsSwitch.setChecked(gpsEnable);

    }


    @Override
    protected void onStop() {
        super.onStop();
        getContentResolver().unregisterContentObserver(mGpsMonitor);
    }


    /**
     * 初始化得到所有按钮对象
     */
    private void initView() {
        main_page_btn1 = findViewById(R.id.main_page_btn1);
        main_page_btn2 = findViewById(R.id.main_page_btn2);
        main_page_btn3 = findViewById(R.id.main_page_btn3);
        gpsSwitch = findViewById(R.id.gps_switch);
        personExit = findViewById(R.id.person_exit);
        personInfo = findViewById(R.id.person_info);

        main_page_btn1.setOnClickListener(this);
        main_page_btn2.setOnClickListener(this);
        main_page_btn3.setOnClickListener(this);
        personExit.setOnClickListener(this);
        personInfo.setOnClickListener(this);

    }

    private void setSecondMenuVisible(boolean visible) {
        LinearLayout second_menu = findViewById(R.id.second_menu);
        if (visible) {
            if (!isSecondMenuLoad) {
                LayoutInflater.from(this).inflate(R.layout.second_page, second_menu);
                isSecondMenuLoad = true;
            }
            second_menu.setVisibility(View.VISIBLE);
        } else {
            second_menu.setVisibility(View.GONE);
        }
    }

    /**
     * 按钮方法映射
     *
     * @param view view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_page_btn1:
                setSecondMenuVisible(findViewById(R.id.second_menu).getVisibility() != View.VISIBLE);
                inspection_input = findViewById(R.id.inspection_input);
                inspection_check = findViewById(R.id.inspection_check);
                inspection_check.setOnClickListener(this);
                inspection_input.setOnClickListener(this);
                break;
            case R.id.main_page_btn2:
                startActivity(new Intent(this, TaskCheckActivity.class).putExtra("name", name));
                break;
            case R.id.main_page_btn3:
                startActivity(new Intent(this, ExecutionInput.class).putExtra("name", name));
                break;
            case R.id.person_exit:
//                Toast.makeText(this,"点击了用户注销按钮",Toast.LENGTH_SHORT).show();
//                Log.d(TAG, "onClick: personExit");
                openPersonExitDialog();
                break;
            case R.id.person_info:
                Toast.makeText(getBaseContext(), "点击了用户信息按钮", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "onClick: personInfo");
                break;
            case R.id.inspection_input:
                startActivity(new Intent(this, InspectionInput.class).putExtra("name", name));
                break;
            case R.id.inspection_check:
                startActivity(new Intent(this, InspectionCheck.class));
                break;
            default:
                break;
        }
    }


    private void initSlidingPaneLayout() {
        // 设置侧划后首页上透明，不带颜色，不会变灰色
        slidingPaneLayout.setSliderFadeColor(Color.TRANSPARENT);
        // 拿到左侧菜单栏view
        final View leftView = slidingPaneLayout.getChildAt(0);
        slidingPaneLayout.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() {
            @Override
            public void onPanelSlide(@NonNull View panel, float slideOffset) {
                // 划动过程中
                // 左侧边栏的变化
                leftView.setPivotX(-leftView.getWidth() / 5.0f);
                leftView.setPivotY(leftView.getHeight() / 2.0f);
                leftView.setScaleX(0.8f + 0.2f * slideOffset);//0.8~1
                leftView.setScaleY(0.8f + 0.2f * slideOffset);//0.8~1
                leftView.setAlpha(0.8f + 0.2f * slideOffset);//0.8~1
                // 首页的变化
                panel.findViewById(R.id.ll_main).setScaleX(1f - 0.2f * slideOffset);
                panel.findViewById(R.id.ll_main).setScaleY(1f - 0.2f * slideOffset);
                // 背景阴影图片的变化
                panel.findViewById(R.id.img_shadow).setScaleX(1f - 0.1f * slideOffset);
                panel.findViewById(R.id.img_shadow).setScaleY(1f - 0.13f * slideOffset);
                panel.findViewById(R.id.img_shadow).setAlpha(1f - 0.3f * slideOffset);
            }

            @Override
            public void onPanelOpened(@NonNull View view) {
            }

            @Override
            public void onPanelClosed(@NonNull View panel) {
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再滑动一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            super.onBackPressed();
            System.exit(0);
        }

    }


    //监听gps状态
    private final ContentObserver mGpsMonitor = new ContentObserver(null) {
        @Override
        public void onChange(boolean change) {
            super.onChange(change);
            checkGPSStates();
        }
    };


    //检查是否打开手机的gps
    public static boolean checkGPSIsOpen() {
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    }

    //改变GPS状态标记
    public void checkGPSStates() {
        gpsEnable = checkGPSIsOpen() ? true : false;
    }

    //在用户需要开启gps时候的调用
    public void enableLocationSettings() {
        Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(settingsIntent);
    }

    private Gps getLatitudeAndLongitude() {
//        if (ActivityCompat.checkSelfPermission(getApplicationContext(),
//                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(),
//                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//           // Toast.makeText(MainPageActivity.this, "没有GPS权限！请授权", Toast.LENGTH_SHORT).show();
//            return null;
//        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return null;
        }
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度，如果设置为高精度，依然获取不了location。
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(true);//允许有花费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
        String locationProvider = locationManager.getBestProvider(criteria, true);

        if (locationProvider==null){
            return null;
        }
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            Gps gpsInfo = new Gps(name, location.getLatitude() + "," + location.getLongitude(), "1");
            return gpsInfo;
        }
        return null;
    }


    /**
     * 开启注销弹窗
     */
    public void openPersonExitDialog() {
        // 1.创建builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(MainPageActivity.this);

        //设置标题
        builder.setTitle("注销确认");
        builder.setIcon(R.drawable.ic_person_exit);//设置标题图片
        //设置内容
        builder.setMessage("\n" + "   确定注销吗？");

        //设置按钮
        // Positive 积极的 正确面
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                MainPageActivity.this.startActivity(new Intent(MainPageActivity.this, LoginActivity.class));
                MainPageActivity.this.finish();
            }
        });
        //Negative 消极的
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(MainPageActivity.this, "cancel", Toast.LENGTH_SHORT).show();
            }
        });
        //调用 builder的create
        AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(Color.WHITE);
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setBackgroundColor(Color.WHITE);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

}